import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { TranslateService } from '@ngx-translate/core';
import { DeviceDetectorService } from 'ngx-device-detector';
import { MessageUtilsService } from '../shared/services/message-utils.service';
import { UserService } from '../shared/services/user.service';
import { LoginService } from '../login/common-service/login.service';
import {DomSanitizer} from '@angular/platform-browser';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  videoUrl: any = '';

  constructor(private httpClient: HttpClient,
    private sanitizer: DomSanitizer,
    private router:Router,
    private loginService:LoginService,
    private userService:UserService,
    private translate: TranslateService,
    private messageUtilsService:MessageUtilsService,
    private deviceService: DeviceDetectorService
    ) { }

  ngOnInit() {
    console.log('isDesktop?',this.deviceService.isDesktop());
    console.log('isMobile?',this.deviceService.isMobile());
    console.log('isTablet?',this.deviceService.isTablet());
    this.userService.getCurrentUser().subscribe(
      (user)=>{
        console.log("home get session {}",user);
        this.router.navigate(['/'+user.role]);
      },
      (err)=>{
        console.log("not login session");
      }
    );
    this.getVideo();
    // return this.loginService.isAuthenticated(["agent"]).pipe(
    //   map(e => {
    //       if (e) {
    //           return true;
    //       }
    //       this.router.navigate(['/login']);
    //       return false;
    //   }),
    //   catchError((err) => { 
    //       console.log("no login so redirect");
    //       this.router.navigate(['/login']);
    //       return throwError(err); 
    //   })
  // );
  }

  getVideo() {
    this.userService.getMainContent().subscribe(
      (data)=>{
        data = data[0] || {};
        const { content1 } = data;
        if (content1) {
          // http://v.qq.com/iframe/player.html?vid=${vid}frswa&width=500&height=375&auto=0
          this.videoUrl = this.sanitizer.bypassSecurityTrustResourceUrl(data.content1);
        }
      },
      (err)=>{
        console.log(err.message);
      }
    );
  }

  isDesktop(){
    return this.deviceService.isDesktop();
  }

  test(){
    alert("d");
    this.httpClient.get<any>(`http://localhost/echo`,{
      withCredentials: true,
      headers: new HttpHeaders().set('Content-Type','application/json')
    }).subscribe(
      data =>{
        console.log(data);
      },
      err=>{
        console.log(err);
      }
    )
  }

  changeLang(language: string) {
    this.translate.use(language);
  }

}
